<template>
  <div class="white-module module">
    <div class="title-h"><span></span>账号信息</div>
    <div class="account-module">
      <div class="register">
        <div class="c">
          <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="140px"
              class="term-ruleForm"
              :size="formSize"
              status-icon
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户类型" >
                  {{baseService.userType(ruleForm.roleId)}}
                </el-form-item>
                <el-form-item label="姓名" >
                  {{ruleForm.realName}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当前代表队：" v-if="!(ruleForm.roleId && ruleForm.roleId.includes('2')) && teamForm.account">
                  {{teamForm.teamName}}
                  <el-button
                      v-if="!unbindStatus"
                      type="text"
                      style="margin-left: 10px;"
                      @click="applyUnbind">申请解绑</el-button>
                  <span v-else style="margin-left: 10px;color: #999;">
                    申请解绑中，{{unbindDays}}天后将自动解绑
                  </span>
                </el-form-item>
                <el-form-item label="当前领队：" v-if="!(ruleForm.roleId && ruleForm.roleId.includes('2'))  && teamForm.realName">
                  {{teamForm.realName}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系方式">
                    <el-select v-model="ruleForm.code" style="width: 90px;">
                      <el-option value="" label="+86"></el-option>
                      <el-option value="852" label="+852"></el-option>
                      <el-option value="853" label="+853"></el-option>
                    </el-select>
                  <el-input v-model.trim="ruleForm.phone" style="width: 130px;margin-left: 2px;" placeholder="请输入"/>
                  <span class="btn-code" v-if="ruleForm.phone!=ruleForm.oldPhone" @click="sendCode">{{btns.sendmsg}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式：" v-if="!(ruleForm.roleId && ruleForm.roleId.includes('2'))  && teamForm.phone">
                  {{teamForm.phone}}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="ruleForm.phone!=ruleForm.oldPhone">
              <el-col :span="12">
                <el-form-item label="验证码" prop="password" >
                  <el-input v-model.trim="ruleForm.password" placeholder="请输入" style="width: 220px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="性别" >
                  <el-radio-group v-model="ruleForm.sex">
                    <el-radio label="1">男</el-radio>
                    <el-radio label="0">女</el-radio>
                  </el-radio-group>
                </el-form-item>

              </el-col>
              <el-col :span="12">
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="证件类型">
                  <!-- 5 其他 -->
                  {{ruleForm.idType === '1' ? '居民身份证' : ruleForm.idType === '2' ? '临时身份证' : ruleForm.idType === '3' ? '港澳居民来往内地通行证' : ruleForm.idType === '4' ? '台湾居民来往大陆通行证' : ruleForm.idType === '5' ? '护照/其他' : ''}}
                </el-form-item>

              </el-col>
              <el-col :span="12">

              </el-col>
            </el-row>


            <el-row>
              <el-col :span="12">
                <el-form-item label="证件号码" >
                  {{baseService.hideIdCard(ruleForm.idCard)}}
                </el-form-item>

              </el-col>
              <el-col :span="12">

              </el-col>
            </el-row>


            <el-row>
              <el-col :span="12">
                <el-form-item label="参赛单位" v-if="sysParams.updUserCompany=='1'">
                  <el-input v-model.trim="ruleForm.company" placeholder="请输入" style="width: 220px;"/>
                </el-form-item>
                <el-form-item label="参赛单位" v-else>
                  {{ruleForm.company}}
                </el-form-item>
              </el-col>
              <el-col :span="12">

              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="单位地址" >
                  <el-input v-model.trim="ruleForm.address" placeholder="请输入" style="width: 220px;"/>
                </el-form-item>

              </el-col>
              <el-col :span="12">

              </el-col>
            </el-row>


            <el-row>
              <el-col :span="12">
                <el-form-item label="电子邮箱" >
                  <el-input v-model.trim="ruleForm.email" placeholder="请输入" style="width: 220px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">

              </el-col>
            </el-row>


            <el-row>
              <el-col :span="24">
                <el-form-item label="一寸证件照" prop="header" v-if="sysParams.updUserImg == '1'">
                  <el-upload
                      class="avatar-uploader"
                      :action="baseUrl+'/front/upload'"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                  >
                    <div class="image" style="width: 100px; height: 140px;">
                      <img v-if="ruleForm.header" :src="ruleForm.header" class="img" />
                      <div v-else class="upload">
                        <img src="@/assets/common/upload.png">
                        <div class="text">上传一寸照片</div>
                      </div>
                    </div>
                    <div class="hint">
                      支持JPG/JPEG/PNG格式，不超过1MB，本信息将导入证件制作系统，<br/>
                      请上传本人一寸近照！
                      <p>点击图片可修改</p>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="一寸证件照" prop="header" v-else>
                  <div class="image" style="width: 100px; height: 140px;">
                    <img v-if="ruleForm.header" :src="ruleForm.header" style="width: 100px; height: 140px;"/>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="0">

              </el-col>
            </el-row>

            <br/>
            <el-form-item>
              <div class="btns">
                <el-button v-if="userInfo.roleId!=='3' && !userInfo.roleId.includes('2')" type="primary" @click="showAddTeacherUserType" style="width:180px;">增补指导老师用户类型</el-button>
                <el-button v-if="userInfo.roleId==='3' && sysParams.upgradeTeacher=='1' && isSlow18(userInfo.idCard)" type="primary" @click="showUpgradeTeacher">升级成指导老师</el-button>
                <el-button type="primary" :loading="isLoading" @click="submitForm(ruleFormRef)">
                  确认修改
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>

  <!--升级成老师-->
  <el-dialog v-model="upgradeTeacherVisible"  :show-close="false" width="450px" >
    <el-form
        ref="ruleForm2Ref"
        :model="ruleForm2"
        label-width="120px"
        class="ruleForm"
        :size="formSize"
        status-icon
    >
      <el-form-item label="联系方式(手机)">
        {{userInfo.phone}}
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model.trim="ruleForm2.password" placeholder="请输入" style="width: 100px;"/>
        <span class="btn-code" @click="sendCode2">{{btns.sendmsg}}</span>
      </el-form-item>
      <el-form-item>
        <div class="btns">
          <el-button @click="upgradeTeacherVisible = false">关闭</el-button>
          <el-button type="primary" @click="upgradeTeacher">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--增补指导老师属性-->
  <el-dialog v-model="addTeacherUserTypeVisible" :show-close="false" width="450px" >
    <el-form
        ref="ruleForm2Ref"
        :model="ruleForm2"
        label-width="120px"
        class="ruleForm"
        :size="formSize"
        status-icon
    >
      <el-form-item label="联系方式(手机)">
        {{userInfo.phone}}
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model.trim="ruleForm2.password" placeholder="请输入" style="width:100px;"/>
        <span class="btn-code" @click="sendCode2">{{btns.sendmsg}}</span>
      </el-form-item>
      <el-form-item>
        <div class="btns">
          <el-button @click="addTeacherUserTypeVisible = false">关闭</el-button>
          <el-button type="primary" @click="addTeacherUserType">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>
<script lang="ts" setup>
import app from "@/constants/app";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from 'element-plus'
import baseService from "@/service/baseService";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import {getCache, removeCache, setCache} from "@/utils/cache";

const imageUrl = ref('')
const imageUrl2 = ref('')
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const baseUrl = app.api;
let router = useRouter();
const ruleForm = reactive({
  id: null,
  email: "",
  realName: '',
  sex: "",
  idType: "",
  idCard: "",
  phone: "",
  password: "",
  code: "",
  header: "",
  company: "",
  oldPhone: "",
  isShowPass: false,
  roleId: null,
  address: ''
});
const btns = reactive({
  sendmsg: "发送验证码",
  disabled: false
});

const rules = reactive<FormRules>({
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  realName: [{ required: true, message: "请输入领队姓名", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  idType: [{ required: true, message: "请选择证件", trigger: "change", }],
  idCard: [{ required: true, message: "请输入证件号码", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  header: [{ required: true, message: "请上传头像", trigger: "blur" }],
});

const isLoading = ref(false);
const teamForm = reactive({
  teamId: null,
  teamName: null,
  account: null,
  realName: null,
  phone: null
});

//取缓存里的用户id
const userCache = getCache('CacheToken', { isSessionStorage: true }, {});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  isLoading.value = true;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 拷贝对象
      let registerForm = JSON.parse(JSON.stringify(ruleForm));
      registerForm.phone = ruleForm.code + ruleForm.phone;
      baseService
          .post("/front/spuser/update", registerForm)
          .then((res) => {
                if (res.code === 0) {
                  ElMessage.success("修改成功");
                  userInfo.header = ruleForm.header;
                  //修改过手机号重新登录
                  if(ruleForm.phone != ruleForm.oldPhone){
                    //延迟1s执行
                    setTimeout(()=>{
                      router.push('/');
                    },1000)
                  }else{
                    //更新缓存
                    setCache('CacheToken', userInfo, true);
                    router.push('/info');
                  }

                } else {
                  ElMessage.error(res.msg);
                }
              }
          ).finally(() => isLoading.value = false);

    } else {
      console.log("error submit!", fields);
    }
  });
};

const teamInfo = getCache('userInfo', { isSessionStorage: true }, {})
const userInfo = getCache('CacheToken', { isSessionStorage: true }, {})
debugger
ruleForm.id = userInfo.id;
ruleForm.email = userInfo.email;

// 从缓存中拿到手机号，如果是香港或者澳门的手机号，去掉852或者853，回显到页面上
if(userInfo.phone.indexOf("852")==0){
  ruleForm.code = "852";
  ruleForm.phone = userInfo.phone.substr(3, userInfo.phone.length);
  ruleForm.oldPhone = userInfo.phone.substr(3, userInfo.phone.length);
}else if(userInfo.phone.indexOf("853")==0){
  ruleForm.code = "853";
  ruleForm.phone = userInfo.phone.substr(3, userInfo.phone.length);
  ruleForm.oldPhone = userInfo.phone.substr(3, userInfo.phone.length);
}else{
  ruleForm.code = "";
  ruleForm.phone = userInfo.phone;
  ruleForm.oldPhone = userInfo.phone;
}

ruleForm.realName = userInfo.realName;
ruleForm.sex = userInfo.sex+'';
ruleForm.header = userInfo.header;
ruleForm.idType = userInfo.idType;
ruleForm.idCard = userInfo.idCard;
ruleForm.company = userInfo.company;
ruleForm.roleId = userInfo.roleId;
ruleForm.address = userInfo.address;

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  //后退
  router.back();
};

const upgradeTeacherVisible = ref(false);
const addTeacherUserTypeVisible = ref(false);
const ruleForm2 = reactive({
  code: "",
  phone: "",
  password: "",
});


const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.header = response.data.src;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg')) {
    ElMessage.error('仅支持JPG/JPEG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('一寸证件照不能超过2MB!')
    return false
  }
  return true
}



/**
 * 发送验证码
 */
const sendCode=()=>{
  //校验ruleForm.name不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  // 校验手机号格式
  if(!checkPhone()){
    return;
  }
  if(btns.disabled) {
    return;
  }
  btns.sendmsg = "验证码已发送";
  //查询用户信息
  baseService
      .post("/front/spuser/queryUserByPhone", {
        realName: ruleForm.realName,
        phone: ruleForm.code + ruleForm.phone
      })
      .then((res) => {
            if (res.code === 0) {
              //用户存在
              ElMessage.error('手机号已存在不可修改');
              ruleForm.phone = ruleForm.oldPhone;
              btns.sendmsg = "发送验证码";
            } else {
              baseService
                  .post("/front/spuser/getCheckCode",{phone: ruleForm.code+ruleForm.phone})
                  .then((res) =>
                      {
                        if (res.code === 0) {
                          ElMessage.success('验证码发送成功');
                          countDown();
                        }
                      }
                  );
            }
          }
      );
};

/**
 * 发送验证码
 */
const sendCode2=()=>{
  btns.sendmsg = "验证码已发送";
  baseService
      .post("/front/spuser/getCheckCode",{phone: userInfo.phone})
      .then((res) =>
          {
            if (res.code === 0) {
              ElMessage.success('验证码发送成功');
              countDown();
            }
          }
      );
}


// 校验手机号格式
const checkPhone = () => {
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号格式不正确！");
    return false;
  }
  // 判断国际区号
  if (ruleForm.code === '') {
    if(ruleForm.phone.length != 11){
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  } else if(ruleForm.code === '852') {
    if(!(ruleForm.phone.length == 8 || ruleForm.phone.length == 9)){
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  } else if(ruleForm.code === '853') {
    if(ruleForm.phone.length != 8){
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  }
  return true;
};


/**
 * 短信验证码倒计时功能
 */
let timer: any = null;
const countDown = () => {
  let count = 60;
  btns.disabled = true;
  btns.sendmsg = count + "s后重新发送";
  timer = setInterval(() => {
    count--;
    btns.sendmsg = count + "s后重新发送";
    if (count <= 0) {
      clearInterval(timer);
      btns.sendmsg = "发送验证码";
      btns.disabled = false;
    }
  }, 1000);
};


/**
 * 查询用户信息
 * @param formEl
 */
const queryUserById = async () => {
  if(!userInfo.id){
    return;
  }
  baseService
      .get("/front/spuser/queryUserById?id="+userInfo.id, {
      })
      .then((res) => {
            if (res.code === 0) {
              let data = res.data;
              teamForm.teamId = data.teamId;
              teamForm.teamName = data.teamName;
              teamForm.account = data.account;
              teamForm.realName = data.realName;
              teamForm.phone = data.phone;
            } else {
              ElMessage.error(res.msg);
            }
          }
      );
};

const showUpgradeTeacher=()=>{
  upgradeTeacherVisible.value = true;
}

const showAddTeacherUserType=()=>{
  addTeacherUserTypeVisible.value = true;
}

const addTeacherUserType=()=>{
  // 确认是否添加指导老师用户类型
  ElMessageBox.confirm('确认增补指导老师用户类型？', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(e => {
    //调用接口
    baseService
        .get("/front/spuser/addTeacherUserType?id=" + userInfo.id + "&password=" + ruleForm2.password, {})
        .then((res) => {
          if (res.code == 0) {
            ElMessage.success("增补成功");
            //重新登录
            removeCache('CacheToken', true);
            removeCache('userInfo', true);
            setTimeout(() => {
              router.push('/');
            }, 1000)
          } else {
            ElMessage.error(res.msg);
          }
        });
  }).catch(e => {
  });
}


/**
 * 升级成老师
 */
const upgradeTeacher=()=> {
  //校验验证码不能为空
  if (ruleForm2.password == "") {
    ElMessage.error("验证码不能为空");
    return;
  }
  //弹出确认框
  ElMessageBox.confirm('升级为指导老师后，将无法恢复选手身份，是否确认升级？', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(e => {
    //调用接口
    baseService
        .get("/front/spuser/upgradeTeacher?id=" + userInfo.id + "&password=" + ruleForm2.password, {})
        .then((res) => {
          if (res.code == 0) {
            ElMessage.success("升级成功");
            //关闭弹窗
            upgradeTeacherVisible.value = false;
            //重新登录
            removeCache('CacheToken', true);
            removeCache('userInfo', true);
            setTimeout(() => {
              router.push('/');
            }, 1000)
          } else {
            ElMessage.error(res.msg);
          }
        });
  }).catch(e => {
  });
}


// 在data/reactive部分添加
const unbindStatus = ref(false);
const unbindDays = ref(0);

// 添加方法
const applyUnbind = () => {
  ElMessageBox.confirm('确认申请解绑当前代表队？', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    baseService
        .post("/front/spteamuser/applyUnbind", {userId: ruleForm.id, teamId: userCache.teamId})
        .then((res) => {
          if (res.code === 0) {
            ElMessage.success("解绑申请已提交");
            unbindStatus.value = true;
            // 假设接口返回解绑天数，如果没有则默认7天
            unbindDays.value = res.data?.unbindDays || 7;
          } else {
            ElMessage.error(res.msg);
          }
        });
  }).catch(() => {});
};


/**
 * 查询用户信息
 * @param formEl
 */
const teamUserId = async () => {
  if(userCache.teamId) {
    baseService
        .post("/front/spteamuser/teamUserId", {userId: ruleForm.id, teamId: userCache.teamId})
        .then((res) => {
              if (res.code === 0) {
                let data = res.data;
                unbindStatus.value = data.status == '1' ? true : false;
                unbindDays.value = res.data?.diff || 0;
              } else {
                ElMessage.error(res.msg);
              }
            }
        );
  }
};

//根据身份证判断是否慢18岁
const isSlow18 = (idCard: string): boolean => {
  debugger
  // 校验18位身份证格式
  if (!/^\d{17}[\dXx]$/.test(idCard) || idCard.length !== 18) {
    throw new Error('Invalid 18-digit ID card format');
  }

  // 提取出生年份（18位身份证的第7-10位）
  const birthYear = parseInt(idCard.slice(6, 10));

  // 获取当前年份
  const currentYear = new Date().getFullYear();

  // 判断出生年份是否小于等于(当前年份-16)
  let isSlow = birthYear <= currentYear - 16;
  debugger
  return birthYear <= currentYear - 16;
};

const sysParams = ref({});
const querySysParams = async()  => {
  baseService.get('/front/spmatch/sysParams').then(e => {
    sysParams.value = e.data;
  })
};


queryUserById();
teamUserId();
querySysParams();


</script>


<style lang="scss" scoped>
@import "../account/account";

.title-h {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: $font-weight-bold;
  padding: 24px 24px 0px;


  span {
    width: 4px;
    height: 12px;
    background: #00a0e9;
    margin-right: 7px;
  }
}

.account-module .register,
.account-module {
  width: 100%;
  height: auto;
  display: block;
  background: none;

  .c .term-ruleForm {

    padding: 0px;
    margin-top: 10px;
    margin-left: 30px;

    .btn-code {
      width: 98px;
      line-height: 32px;
      background: #EFF6FF;
      border-radius: 4px;
      text-align: center;
      color: $color-primary;
      margin-left: 12px;

    }

    .btns {
      width: 100%;
      margin-left: 275px;
      margin-top: 12px;
      display: block;
    }
  }

  .c .uplods {
    top: 231px;
    display: flex;
    left: 480px;
    right: inherit;
    margin-right: 52px;

    .avatar-uploader {

      margin-right: 52px;
    }
  }
}
</style>


